<?php

namespace app\store\controller\apps\dealer;

use app\common\model\SettingLog as SettingLogSettingModel;
use app\store\controller\Controller;
use app\store\model\dealer\Setting as SettingModel;
use app\store\model\Goods as GoodsModel;
use app\store\model\dealer\DistributionSetting as DistributionSettingModel;
use app\store\model\Wxapp as WxappModel;
use think\Session;

/**
 * 分销设置
 * Class Setting
 * @package app\store\controller\apps\dealer
 */
class Setting extends Controller
{
    /**
     * 分销设置
     * @return array|bool|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function index()
    {
        if (!$this->request->isAjax()) {
            $data = SettingModel::getAll();
            // 购买指定商品成为分销商：商品列表
            $goodsList = (new GoodsModel)->getListByIds($data['condition']['values']['become__buy_goods_ids']);
            return $this->fetch('index', compact('data', 'goodsList'));
        }
        $model = new SettingModel;
        if ($model->edit($this->postData('setting'))) {
            return $this->renderSuccess('更新成功');
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    /**
     * 分销海报
     * @return array|mixed
     * @throws \think\exception\PDOException
     */
    public function qrcode()
    {
        if (!$this->request->isAjax()) {
            $data = SettingModel::getItem('qrcode');
            return $this->fetch('qrcode', [
                'data' => json_encode($data, JSON_UNESCAPED_UNICODE)
            ]);
        }
        $model = new SettingModel;
        if ($model->edit(['qrcode' => $this->postData('qrcode')])) {
            return $this->renderSuccess('更新成功');
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    /*
    * 分销方案一设置
    */
    public function oneset(){



        $dealer_type = 1;
        if (!$this->request->isAjax()) {
            $wxappId = Session::get('yoshop_store')['wxapp']['wxapp_id'];
            //获取分销方案
            $dealerCase = WxappModel::dealerCase($wxappId);
            $detail = DistributionSettingModel::getItem($dealer_type,$wxappId);
            if($detail){
                $data = json_decode($detail['setting_content'],true);
                $data['id'] = $detail['id'];
            }else{
                $data['distribution_con'] = 0;
                $data['distribution_type'] = 0;
                $data['consume_charge'] = 0;
                $data['id'] = 0;
                $data['product_status'] = 2;
                $data['card_status'] = 2;
                $data['hot_sale_status'] = 2;
                $data['status'] = 2;
                $dealerCase = 0;
            }
            return $this->fetch('oneset', ['data'=>$data,'dealerCase'=>$dealerCase] );
        }

        $model = new DistributionSettingModel;

        $id = $this->postData('distributionSetting')['id'];
        $dealerCase = input('dealerCase');

        $setting_content = $this->postData('distributionSetting');

        $setting_content['dealerCase'] = $dealerCase;
        //写入日志
        $settingLog = new SettingLogSettingModel();
        //设备类型
        $deviceType = getDeviceType();

        $logData = [
            'type'=>3,//1：分红设置  2：会员卡分红设置 3：分销方案一 4：分销方案二
            'create_time'=>time(),
            'client'=>"分销方案一",
            'deviceType'=>$deviceType,
            'wxapp_id'=>$this->getWxappId()
        ];

        if($id){
            if($model->edit($id,$this->postData('distributionSetting'),$dealerCase)) {
                $settingLog->addData($logData,$setting_content);
                return $this->renderSuccess('更新成功');
            }
            return $this->renderError($model->getError() ?: '更新失败');
        }
        if($model->add($this->postData('distributionSetting'),$dealer_type,$dealerCase)) {
            $settingLog->addData($logData,$setting_content);
            return $this->renderSuccess('添加成功');
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }


    /*
    * 分销方案二设置
    */
    public function towset(){

        $dealer_type = 2;

        if (!$this->request->isAjax()) {

            $wxappId = Session::get('yoshop_store')['wxapp']['wxapp_id'];
            //获取分销方案
            $dealerCase = WxappModel::dealerCase($wxappId);

            $detail = DistributionSettingModel::getItem($dealer_type,$wxappId);

            if($detail){
                $data = json_decode($detail['setting_content'],true);
                if(!isset($data['staff'])){
                    $data['staff'] = [
                        'dealer_percent'=>0,
                        'face_status'=>2,
                        'product_status'=>2,
                        'card_status'=>2,
                        'gifts_status'=>2,
                    ];
                }
                $data['id'] = $detail['id'];

            }else{

                $data = [
                    'common'=>[
                        'dealer_percent'=>0,
                        'face_status'=>2,
                        'product_status'=>2,
                        'card_status'=>2,
                        'gifts_status'=>2,
                    ],
                    'staff'=>[
                        'dealer_percent'=>0,
                        'face_status'=>2,
                        'product_status'=>2,
                        'card_status'=>2,
                        'gifts_status'=>2,
                    ],
                    'wgd'=>[
                        'dealer_percent'=>0,
                        'face_status'=>2,
                        'product_status'=>2,
                        'card_status'=>2,
                        'gifts_status'=>2,
                    ],
                    'vip'=>[
                        'face_status'=>2,
                        'product_status'=>2,
                        'card_status'=>2,
                        'gifts_status'=>2,
                    ],
                    'dealerCase' => 0,
                    'id' => 0,

                ];
            }
            return $this->fetch('towset', ['data'=>$data,'dealerCase'=>$dealerCase] );
        }



        $postData = $this->postData();

        $model = new DistributionSettingModel;

        $id = $postData['id'];

        //写入日志
        $settingLog = new SettingLogSettingModel();
        //设备类型
        $deviceType = getDeviceType();
        $logData = [
            'type'=>4,//1：分红设置  2：会员卡分红设置 3：分销方案一 4：分销方案二
            'create_time'=>time(),
            'client'=>"分销方案二",
            'deviceType'=>$deviceType,
            'wxapp_id'=>$this->getWxappId()
        ];

        if($id){
            if($model->edittow($id,$postData)) {
                $settingLog->addData($logData,$postData);
                return $this->renderSuccess('更新成功');
            }
            return $this->renderError($model->getError() ?: '更新失败');
        }
        if($model->addtow($postData,$dealer_type)) {
            $settingLog->addData($logData,$postData);
            return $this->renderSuccess('添加成功');
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }


    /**
     * 日志列表
     */
    public function log(){

        $wxapp_id = $this->getWxappId();

        $filter = [];

        $param = $this->request->param();

        if (isset($param['type']) && !empty($param['type'])) {
            $param['type'] > -1 && $filter['type']  = ['=',$param['type']];
        }

        // 起始时间
        !empty($param['start_time']) && $filter['create_time']  = ['>=',strtotime($param['start_time'])];
        // 截止时间
        !empty($param['end_time']) &&  $filter['create_time']  = ['<',strtotime($param['end_time']) + 86400];

        if(!empty($param['start_time']) && !empty($param['end_time'])){
            $filter['create_time']  = ['between',[strtotime($param['start_time']), strtotime($param['end_time']) + 86400]];
        }



        $list = db('setting_log')
            ->where(['type'=>['in',[3,4]],'wxapp_id'=>$wxapp_id])
            ->where($filter)
            ->order(['create_time desc'])
            ->paginate(6, false, [
                'query' => \request()->request()
            ])->each(function($item,$key){
                $item['create_time'] = date('Y-m-d H:i:s',$item['create_time']);
                $item['values'] = json_decode($item['values'],true);
                return $item;
            });

        return $this->fetch('log', [
            'list' => $list
        ]);


    }

}